package com.itheima.wemedia.service.impl;

import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import com.itheima.wemedia.pojo.WmUser;
import com.itheima.wemedia.mapper.WmUserMapper;
import com.itheima.wemedia.service.WmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;


@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    /**
     * 通过app端用户id查询自媒体人信息
     *
     * @param apUserId
     * @return
     */
    @Override
    public WmUser getByApUserId(Long apUserId) {
        return query().eq("ap_user_id", apUserId).one();
    }

    /**
     * 用户登录校验
     *
     * @param paramMap
     * @return
     */
    @Override
    public Map<String, Object> loginCheck(Map<String, String> paramMap) {
        //1. 获取参数
        String username = paramMap.get("name");
        String password = paramMap.get("password");
        //2. 非空校验
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            throw new LeadNewsException("用户名或密码不能为空");
        }
        //3. 通过用户名查询用户信息
        WmUser wmUser = query().eq("name", username).one();
        //4. 不存在则报用户名或密码错误
        if(null == wmUser){
            throw new LeadNewsException("用户名或密码错误");
        }
        //5. 存在 则要校验密码是否相同
        //5.1 前端密码加盐加密
        password+=wmUser.getSalt();
        String encryptedPwd = DigestUtils.md5DigestAsHex(password.getBytes());
        //5.2 密码比对
        if(!encryptedPwd.equals(wmUser.getPassword())) {
            //5.3 不同则报用户名或密码错误
            throw new LeadNewsException("用户名或密码错误");
        }
        //6. 创建token
        String token = AppJwtUtil.createToken(wmUser.getId());
        //7. 构建返回的map
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("token", token);
        wmUser.setPassword(null);
        wmUser.setSalt(null);
        resultMap.put("user", wmUser);
        return resultMap;
    }
}
